<script>
import JSelectUserByDepModalV2 from '@comp/jeecgbiz/modal/JSelectUserByDepModalV2.vue'
import { getAction } from '@api/manage'

export default {
  name: 'SelectMaterialByCategoryModal',
  components: { JSelectUserByDepModalV2 },
  data() {
    return {
      title: '选择物料',
      visible: false,
      disableSubmit: false,
      categoryDataList: [],
      url: {
        list: '/goods/erpGoodsCategory/queryTopList',
        childList: '/goods/erpGoodsCategory/childList',
        queryMaterialList: '/base/erpGoods/queryListByCondition',
        queryMaterialList2: '/base/erpGoods/list',
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 30,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'code',
          width: 147,
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'name',
          width: 147,
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'noneSpec',
          width: 147,
        },
        {
          title: '物料描述',
          align: 'center',
          dataIndex: 'categoryDescription',
          width: 100,
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'meUnit_dictText',
          width: 60,
        },
        {
          title: '辅单位',
          align: 'center',
          dataIndex: 'auUnit_dictText',
          width: 60,
        },
        {
          title: '换算率',
          align: 'center',
          dataIndex: 'coRate',
          width: 60,
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'classify',
          width: 100,
        },
        {
          title: '保质期',
          align: 'center',
          dataIndex: 'qualityDays',
          width: 60,
        },
        {
          title: '客户物料编码',
          align: 'center',
          dataIndex: 'customCode',
          width: 60,
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerName',
          width: 100,
        },
        {
          title: '品牌',
          align: 'center',
          dataIndex: 'brand',
          width: 100,
        },
        {
          title: '单位/Tray',
          align: 'center',
          dataIndex: 'unitTray',
          width: 60,
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createBy',
          width: 60,
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 60,
        },
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      loading: false,
      checkSelectRows: [],
      selectedRowKeys: [],
      selectionRows: [],
      // 查询逻辑按照 系统管理-物料信息搬过来的，不要问为啥用两个接口查询数据
      currentUrl: null,
      warehouseCode: '',
      queryParam: {
        pageNo: 1,
        pageSize: 10,
      },
      queryParam2: {
        pageNo: 1,
        pageSize: 10,
        name: null,
        code: null,
      },
    }
  },
  mounted() {
    this.fetchCategoryData()
  },
  methods: {
    handleConfirm() {
      this.$emit('confirm', this.selectionRows)
      this.close()
    },
    handleCancel() {
      this.close()
    },
    onLoadCategoryData(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        const params = {
          parentId: treeNode.eventKey,
        }
        getAction(this.url.childList, params).then((res) => {
          if (res.success) {
            treeNode.dataRef.children = res.result.records.map((item) => {
              return {
                ...item,
                key: item.id,
                title: item.name,
                isLeaf: item.hasChild !== '1',
              }
            })
            this.categoryDataList = [...this.categoryDataList]
            resolve()
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    showModal(param) {
      if (param && param.warehouseCode) {
        this.warehouseCode = param.warehouseCode
      }
      this.visible = true
    },
    fetchCategoryData() {
      getAction(this.url.list, {}).then((res) => {
        if (!res.success) {
          this.$message.warning(res.message)
          return
        }
        if (res.result.records && res.result.records.length > 0) {
          this.categoryDataList = res.result.records.map((item) => {
            return {
              ...item,
              key: item.id,
              title: item.name,
              isLeaf: item.hasChild !== '1',
            }
          })
        }
      })
    },
    onCategorySelect(selectedKeys, { node: { dataRef } }) {
      this.onClearSelected()
      this.queryParam.id = dataRef.id
      this.queryParam.code = dataRef.code
      this.currentUrl = this.url.queryMaterialList
      this.fetchMaterialData()
    },
    fetchMaterialData() {
      if (this.warehouseCode) {
        this.queryParam.warehouseCode = this.warehouseCode
      }
      getAction(this.currentUrl, this.queryParam).then((res) => {
        if (!res.success) {
          this.$message.warning(res.message)
          return
        }
        let result = res.result
        if (Number(result.total) > 0) {
          this.ipagination.total = Number(result.total)
          this.checkSelectRows = res.result.records
        } else {
          this.checkSelectRows = []
          this.loading = false
        }
      })
    },
    searchQuery() {
      this.currentUrl = this.url.queryMaterialList2
      this.queryParam = JSON.parse(JSON.stringify(this.queryParam2))
      this.fetchMaterialData()
    },
    searchReset() {
      this.queryParam = {
        pageNo: 1,
        pageSize: 10,
      }
      this.currentUrl = this.url.queryMaterialList2
      this.fetchMaterialData()
    },
    onSelectRow(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' === sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.queryParam.pageNo = this.ipagination.current
      this.queryParam.pageSize = this.ipagination.pageSize
      this.fetchMaterialData()
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.queryParam = {
        pageNo: 1,
        pageSize: 10,
      }
      this.queryParam2.name = null
      this.queryParam2.code = null
    },
    close() {
      this.onClearSelected()
      this.$emit('close')
      this.visible = false
    },
  },
}
</script>

<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @ok="handleConfirm"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
  >
    <a-row :gutter="10" style="padding: 10px">
      <a-col :md="6" :sm="24">
        <a-card :bodyStyle="{ padding: '10px' }" style="height: 50vh; overflow-y: auto">
          <a-tree :load-data="onLoadCategoryData" :tree-data="categoryDataList" @select="onCategorySelect" />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="编号">
                  <a-input placeholder="请输入编号" v-model="queryParam2.code"></a-input>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <a-form-item label="名称">
                  <a-input placeholder="请输入名称" v-model="queryParam2.name"></a-input>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="8" :sm="24">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-card :bodyStyle="{ padding: '10px' }" style="height: 50vh">
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
            <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
            >项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <a-table
            ref="table"
            size="middle"
            :scroll="{ x: true }"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="checkSelectRows"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{ selectedRowKeys, onChange: onSelectRow }"
            class="j-table-force-nowrap1"
            @change="handleTableChange"
          >
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </j-modal>
</template>

<style scoped></style>
